package hc.bre.project

import hc.bre.cmn.RuleDefinition
import hc.bre.cmn.RuleScriptBuilder

@groovy.transform.CompileStatic
class PackClassBuilder extends RuleScriptBuilder{
	String packageNode;
	String packPackage;
	List<RuleScriptBuilder> builderList = []
	Map<String , PackClassBuilder> packBuilderChilds =[:]

	StringBuilder buildList(List<RuleScriptBuilder> builderList) {
		builderList.each { builder ->
//			this.add(builder);
			String packageName =  hc.Util.rpathPackageName(builder.ruleDef.rpath);
			add(this,packageName,builder);
		};
		this.buildClass()
		return this.sbOfClass;
	}

//	public void add(RuleScriptBuilder builder) {
//		String packageName =  hc.Util.rpathPackageName(builder.ruleDef.rpath);
//		add(this,packageName,builder);
//	}
	
	@Override
	public StringBuilder buildClass() {
		builderList.each { builder ->
			apdNlBlock(builder.sbOfClass.toString());
		};

		String staticFlag = '';
		if(projectPackage != packPackage) {
			staticFlag = 'static ';
		};

		packBuilderChilds.each{ node, packBuilder ->
			apdNl("${staticFlag}public class ${node}{")
			nested(){
				packBuilder.buildClass();
				apdNlBlock(packBuilder.sbOfClass.toString());
			};
			apdNl("};");
		}
		
		return this.sbOfClass;
	}

	public void add(PackClassBuilder packBuilder, String packageName, RuleScriptBuilder builder) {
		if(packageName == packBuilder.packageNode) {
			packBuilder.builderList.add(builder);
			return;
		};

		assert packageName.startsWith(packBuilder.packageNode);
		packageName = packageName.substring(packBuilder.packageNode.length()+1);

		String node
		int dot = packageName.indexOf('.');
		node = dot>=0 ? packageName.substring(0, dot) : packageName;

		PackClassBuilder child = packBuilderChilds.get(node);
		if(child == null) {

			child = new PackClassBuilder(packageNode:node
			,projectPackage:projectPackage
			,packPackage:packPackage+'.'+node);

			packBuilderChilds.put(node,child);
		}

		add(child,packageName,builder);
	}
}
